// pages/login/login.js
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';

import {
  request
} from '../../api/index'
import {
  formateObjToParamStr
} from '../../utils/util'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    loading: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setPageProperty();
 
  },
  /**
   * 设置页面属性
   */
  setPageProperty() {
    wx.setNavigationBarTitle({
      title: '陶瓷数据采集 - 未登录'
    })
  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /** 
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  setLoading(data) {
    this.setData({
      loading: data
    })
  },
  loginSuccess(res) {
    
    const app = getApp();
    const pages = app.globalData.prevPage ;
    wx.setStorageSync('root', res.root);
    app.globalData.root = res.root;

    try {
      const options = pages[pages.length-1].options;
      const url = pages[pages.length-1].route;
      const route = `/${url}?${formateObjToParamStr(options)}`;
     
      wx.redirectTo({
        url: route
      })
    } catch (error) {
      wx.redirectTo({
        url: '../home/index'
      })
    } finally {
      app.globalData.prevPage = null;
      this.setLoading(false);
    }
  },
  loginFail(msg) {
    
    Toast({
      message: `登录失败: ${msg}`,
      position: 'bottom'
    });
    this.setLoading(false);
  },
  onSubmit(target) {
    if (target && target.detail.value.password && target.detail.value.userName) {
      this.setLoading(true);
      request.login({
        password: target.detail.value.password,
        loginName: target.detail.value.userName
      }, this.loginSuccess, this.loginFail);
    } else {
      Toast({
        message: '请填写账号和密码',
        position: 'bottom'
      });
    }
  }
})